package com.mfz.users

import com.mfz.common.dbHelper.dbHelper
import com.mfz.common.persistence.AbstractFactory
import com.mfz.common.persistence.AbstractPersistence
import com.mfz.common.units.ID
import com.mfz.users.definition.COMPANY_ID

/**
 *
 * create by 2020/1/26.
 * @author zhengyimin
 */
class Role private constructor() : AbstractPersistence(Role), com.mfz.common.definition.organization.Role {
	private lateinit var _ownerCompany: Company

	override val users: Collection<User>
		get() = User.getUsersByRole(id)

	override val ownerCompany: Company
		get() {
			if (!this::_ownerCompany.isInitialized) {
				_ownerCompany = Company.get(ID, get(COMPANY_ID, -1))!!
			}

			return _ownerCompany
		}

	override val isAvailable: Boolean
		get() = flag.notDelete && ownerCompany.isAvailable

	companion object : AbstractFactory<Role>("role") {
		override fun createNewObject(): Role {
			return Role()
		}

		init {
			useBuffer = true
		}


		fun loadCompanyRoles(companyId: Int): List<Role> {
			return getPersistences(" $COMPANY_ID = $companyId")
		}

		fun loadInvolveUsers(userIds: Array<Int>): List<Role> {
			return getPersistences("id = any(${dbHelper.format(userIds)})")
		}
	}
}
